//$Import('PhotoCollection');s

STK.register('albums', function() {
	
	function sprintf(text){
	    var i=1, args=arguments;
	    return text.replace(/\{[a-zA-Z]+\}/g, function(pattern){
	        return (i < args.length) ? args[i++] : "";
	    });
	}
	
	function Album(albumData) {
		this.init(albumData);
	}
	
	Album.prototype.init = function(albumData) {
		this.oriData = albumData;
		this.name = albumData.name;
		this.photos = albumData.detail;
	};
	
	Album.prototype.generateHtml = function() {
		var data = this.formatData();
		var html = '<li>';
		
		html += sprintf('<a href="{href}" title="{title}">', data.href, this.name);
		for(var i = 0, l = data.imgSrc.length; i < l; i++) {
			html +=	sprintf('<img class="{class}" src="{src}">', 'pic' + (i + 1), data.imgSrc[i]);
		}
		html += '</a></li>';
		return html;
	};
	
	Album.prototype.formatData = function() {
		var href = '#photos/' + this.name,
			fourPhotos = this.getPhotos(4),
			imgSrc = [],
			i, cur;
			
		for(i = 0, cur = fourPhotos[0]; cur; i++, cur = fourPhotos[i]) {
			imgSrc.push( 'http://ww1.sinaimg.cn/small/' + fourPhotos[i].key );
		}
		
		return {
			href : href,
			imgSrc : imgSrc
		};
	};
	
	Album.prototype.getPhotos = function(count) {
		return this.photos.slice(0, count);
	};
	
	Album.prototype.getAllPhotos = function() {
		return this.photos;
	};
	
	Album.prototype.getName = function() {
		return this.name;
	};
	
	
	var Albums = {
		init : function(container) {
			this.getData();
			this.render(container);
		},
		getData : function() {
			this.data = STK.PhotoCollection.model.get('data');
		},
		render : function(parent) {
			var data = this.data,
				html = '<ul>';
			for(var i = 0, l = data.length; i < l; i++) {
				var album = new Album(data[i]);
				this.list[album.getName()] = album;
				html += album.generateHtml();
			}
			html += '</ul>';
			parent.innerHTML = html;
		},
		list : {}
	};
	
	return Albums;
		
});
